package com.uwlaser.service.impl;

import com.uwlaser.base.PageInfo;
import com.uwlaser.base.impl.CommonServiceImpl;
import com.uwlaser.domain.AntonRecord;
import com.uwlaser.domain.AntonRecordParam;
import com.uwlaser.service.AntonRecordService;
import com.uwlaser.service.dto.AntonRecordDto;
import com.uwlaser.service.mapper.AntonRecordMapper;
import com.uwlaser.utils.StringUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author yangwei
 * @create 2022/11/30
 */
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = FactoryModelService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AntonRecordServiceImpl extends CommonServiceImpl<AntonRecordMapper, AntonRecord> implements AntonRecordService {
    @Autowired
    private AntonRecordMapper antonRecordMapper;

    @Override
    public PageInfo<AntonRecordDto> queryByParam(AntonRecordParam query, Pageable pageable) {
        //参数开始时间和结束时间不为空 赋值
        if(!CollectionUtils.isEmpty(query.getCreateTime())){
            String beginTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(query.getCreateTime().get(0));
            String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(query.getCreateTime().get(1));
            query.setBeginTime(beginTime);
            query.setEndTime(endTime);
        }
        query.setPageSize(pageable.getPageSize());
        query.setPageNumber(pageable.getPageNumber()*pageable.getPageSize());
        PageInfo<AntonRecordDto> res = new PageInfo<>();
        List<AntonRecordDto> antonRecordDtos = antonRecordMapper.queryByParam(query);
        Long count = antonRecordMapper.selectCountByParam(query);
        res.setContent(antonRecordDtos);
        res.setTotalElements(count);
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(AntonRecord resources) {
        if (StringUtils.isEmpty(resources.getBeginTime())
                || StringUtils.isEmpty(resources.getAntonCode())
                || StringUtils.isEmpty(resources.getConsumeTime())
                || StringUtils.isEmpty(resources.getEndTime())) {

            throw new RuntimeException("参数不能为空!");
        }
        return antonRecordMapper.insert(resources);
    }

}
